﻿/*
 * 文件功能描述：
 * 创建者：
 * 创建时间：
*/
using System;
using System.Collections.Generic;

using System.Text;
using System.Collections;
using System.Reflection;
using System.Data;

namespace Data
{
    /// <summary>
    /// model和DataTable，相互转换
    /// </summary>
    /// <typeparam name="T">Model的类型</typeparam>
    public  class ConvertHelper<T> where T : new()
    {
        /// <summary>
        /// 获取模型对应表字段名
        /// </summary>
        public static string GetCollectionsColumnName()
        {
            PropertyInfo[] propertys = typeof(T).GetProperties();

            string ColumnNames = "";

            foreach (PropertyInfo p in propertys)
            {
                ColumnNames += ",[" + p.Name + "]";
            }

            if (ColumnNames.Length > 0)
            {
                ColumnNames = ColumnNames.Remove(0, 1);
            }

            return ColumnNames;
        }
        /// <summary>
        /// DataTable 转成 T 类型的 model List
        /// </summary>
        /// <param name="dt"></param>
        /// <returns>如果 dt 无row 则返回null</returns>
        public static List<T> ConvertToModelList(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return null;
            }
            // 定义集合
            List<T> ts = new List<T>();
            // 获得此模型的类型
            Type type = typeof(T);
            string tempName = "";

            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                // 获得此模型的公共属性
                PropertyInfo[] propertys = typeof(T).GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;

                    // 检查DataTable是否包含此列
                    if (dt.Columns.Contains(tempName))
                    {
                        // 判断此属性是否有Setter
                        //if (!pi.SetValue) continue;
                        object value = dr[tempName];
                        if (value != DBNull.Value)
                        {
                            if (pi.PropertyType.ToString() == "System.String")
                            {
                                pi.SetValue(t, System.Web.HttpUtility.HtmlDecode(value.ToString()), null);
                            }
                            else
                            {
                                pi.SetValue(t, value, null);
                            }
                        }
                    }
                }
                ts.Add(t);
            }
            return ts;
        }

        /// <summary>
        /// DataTable 转成 T 类型的 model
        /// </summary>
        /// <param name="dt"></param>
        /// <returns>如果列表空，返回model默认值（null,0）。否则，返回列表中第一行记录转换的model</returns>
        public static T ConvertToModel(DataTable dt)
        {
            List<T> list = ConvertToModelList(dt);
            if (list.Count <= 0)
            {
                return default(T);
            }
            return list[0];
        }
        /// <summary>
        /// T类型的model List转成DataTable
        /// </summary>
        /// <param name="Tlis"></param>
        /// <returns></returns>
        public static DataTable ConvertToDT(List<T> Tlis)
        {
            if (Tlis == null || Tlis.Count < 1)
            {
                return null;
            }
            // 定义dt
            DataTable dtret = new DataTable();
            // 获得此模型的类型
            Type type = typeof(T);
            // 获得此模型的公共属性
            PropertyInfo[] propertys = type.GetProperties();
            foreach (PropertyInfo pi in propertys)
            {
                dtret.Columns.Add(pi.Name);
            }
            foreach (T t in Tlis)
            {
                DataRow dr = dtret.NewRow();
                foreach (PropertyInfo pi in propertys)
                {
                    // 检查DataTable是否包含此列
                    if (dtret.Columns.Contains(pi.Name))
                    {
                        if (pi.GetValue(t, null) == null || pi.GetValue(t, null).ToString() == new DateTime().ToString())
                        {
                            dr[pi.Name] = DBNull.Value;
                        }
                        else
                        {
                            dr[pi.Name] = pi.GetValue(t, null);
                        }
                    }
                }
                dtret.Rows.Add(dr);
            }
            dtret.AcceptChanges();
            return dtret;
        }

    }
}